<template>
  <div>
    <div class="banner">
      <!-- <div class="left">
        <div>
          <p class="time">{{ dayjs(updateTime).format("HH:mm:ss") }}</p>
          <p class="date">{{ dayjs(updateTime).year() }}年{{ dayjs(updateTime).month() + 1 }}月{{ dayjs(updateTime).date() }}日</p>
        </div>
        <div>
          <px-button icon="Refresh" type="primary" link @click="queryTable">刷新</px-button>
          <img :src="costumePng" alt="报警时间" />
        </div>
      </div> -->
      <div class="right">
        <img :src="undoPng" alt="当前未处理" />
        <div class="title">
          <p>当前未处理</p>
          <p>{{ sumValue.undoNumber }}</p>
        </div>
      </div>
      <div class="middle">
        <img :src="allPng" alt="报警设备总数" />
        <div class="title">
          <p>报警设备总数</p>
          <p>{{ sumValue.alarmEqpNumber }}</p>
        </div>
      </div>
    </div>
    <div class="equip-wrap-common">
      <px-form ref="searchFormRef" class="custom-form-ui equip-form" :model="queryParams" label-position="right" label-width="120px">
        <px-row :gutter="16">
          <px-col :span="6">
            <px-form-item label="设备状态" prop="eqpStatus">
              <px-select v-model="queryParams.eqpStatus" placeholder="请选择设备状态" clearable filterable>
                <px-option v-for="item in eqpStatusList" :key="item.id" :label="item.label" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col>
          <!-- <px-col :span="6">
            <px-form-item label="工单状态" prop="workOrderStatus">
              <px-select v-model="queryParams.workOrderStatus" placeholder="请选择工单状态" clearable filterable>
                <px-option v-for="item in maintainStatusList" :key="item.id" :label="item.name" :value="item.value" />
              </px-select>
            </px-form-item>
          </px-col> -->
          <px-col :span="6">
            <px-form-item label="设备类型" prop="eqpType">
              <px-tree-select
                v-model="queryParams.eqpType"
                placeholder="请选择设备类型"
                clearable
                filterable
                :data="eqpTypeList"
                :props="{ children: 'children', label: 'name' }"
                node-key="name"
                highlight-current
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备编号" prop="eqpId">
              <px-input
                v-model="queryParams.eqpId"
                placeholder="请输入设备编号"
                maxlength="50"
                @blur="queryParams.eqpId = $event.target.value.trim()"
                @keyup.enter="queryTable"
              >
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="设备名称" prop="eqpName">
              <px-input v-model="queryParams.eqpName" placeholder="请输入设备名称" maxlength="50" @keyup.enter="queryTable">
                <template #suffix>
                  <px-icon style="cursor: pointer" @click="queryTable">
                    <search />
                  </px-icon>
                </template>
              </px-input>
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-form-item label="报警时间" prop="time">
              <px-date-picker
                v-model="queryParams.time"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </px-form-item>
          </px-col>
          <px-col :span="6">
            <px-button type="primary" @click="queryTable">查询</px-button>
            <px-button @click="resetTable">重置</px-button>
          </px-col>
        </px-row>
      </px-form>
      <div v-if="tableData.length === 0" class="empty">
        <img :src="EmptyPng" alt="一切安好 暂无报警" />
        <p>一切安好 暂无报警</p>
      </div>
      <px-table v-if="tableData.length !== 0" :data="tableData" class="equip-table" size="small" height="calc(100vh - 450px)" border>
        <px-table-column type="index" label="序号" width="50" fixed align="center" />
        <px-table-column prop="eqpId" label="设备编号" min-width="150" show-overflow-tooltip />
        <px-table-column prop="eqpName" label="设备名称" min-width="200" show-overflow-tooltip />
        <px-table-column prop="eqpType" label="设备类型" min-width="150" show-overflow-tooltip />
        <px-table-column prop="eqpStatus" label="设备状态" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            <p
              class="status"
              :style="{
                color: `${tagColorList[scope.row.eqpStatus]}`,
                border: `1px solid ${tagBorderColorList[scope.row.eqpStatus]}`,
                backgroundColor: `${tagBgColorList[scope.row.eqpStatus]}`
              }"
            >
              <img v-if="scope.row.eqpStatus === '火警'" :src="firePng" />
              <span>{{ scope.row.eqpStatus }}</span>
            </p>
          </template>
        </px-table-column>
        <!-- <px-table-column prop="eqpStatus" label="工单状态" min-width="100" show-overflow-tooltip>
          <template #default="scope">
            <px-tag
              v-if="scope.row.workOrderStatusDesc"
              effect="plain"
              :style="{
                color: `${tagColorList[scope.row.workOrderStatus]}`,
                border: `1px solid ${tagBorderColorList[scope.row.workOrderStatus]}`,
                backgroundColor: `${tagBgColorList[scope.row.workOrderStatus]}`,
                cursor: 'pointer'
              }"
            >
              {{ scope.row.workOrderStatusDesc }}
            </px-tag>
            <span v-else>-</span>
          </template>
        </px-table-column> -->
        <!-- 616 -->
        <!-- <px-table-column prop="alarmContent" label="报警内容" min-width="300" show-overflow-tooltip /> -->
        <px-table-column prop="eqpPosition" label="设备位置" min-width="200" show-overflow-tooltip />
        <px-table-column prop="alarmTime" label="报警时间" min-width="180" show-overflow-tooltip />
        <px-table-column fixed="right" label="操作" min-width="180" align="center">
          <template #default="scope">
            <px-button v-has="'ERC_ALARM_CLEAR'" link type="primary" @click="handleClear(scope.row)">报警消除</px-button>
            <px-button v-if="scope.row.workOrderStatusDesc" v-has="'ERC_MAINTAIN_HISTORY_DETAIL'" link type="primary" @click="handleView(scope.row)">
              详情
            </px-button>
            <px-button v-else v-has="'ERC_ALARM_MAINTAIN'" link type="primary" @click="handleMaintain(scope.row)">转维修工单</px-button>
          </template>
        </px-table-column>
      </px-table>
      <pagination
        v-if="tableData.length !== 0"
        v-show="total > 0"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        class="equip-table-pagination"
        :total="total"
        @pagination="queryTable"
      />
      <!--取消弹窗-->
      <px-dialog v-model="isCancelShow" title="确定要消除该报警吗？" width="600px" destroy-on-close append-to-body>
        <px-form ref="cancelRef" :model="cancelForm" label-position="top">
          <px-form-item label="报警消除原因" prop="closeReason">
            <px-input
              v-model="cancelForm.closeReason"
              type="textarea"
              :autosize="{ minRows: 3, maxRows: 8 }"
              maxlength="1000"
              clearable
              placeholder="请输入"
              show-word-limit
            />
          </px-form-item>
        </px-form>
        <template #footer>
          <div class="dialog-footer">
            <px-button @click="handleCancelCancel">取消</px-button>
            <px-button type="primary" @click="handleSubmitCancelForm(cancelRef)">确定</px-button>
          </div>
        </template>
      </px-dialog>
    </div>
  </div>
</template>
<script setup lang="ts">
defineOptions({
  name: "ERC_ALARM_REALTIME"
});
import { getAlarmCount, getAlarmEnum, queryAlarmList, updateAlarm } from "@/api/erc/alarm";
import { searchTreeLedger } from "@/api/erc/equip";
import { getStatusList } from "@/api/erc/maintain";
import allPng from "@/assets/images/erc/alarm_all.png";
import EmptyPng from "@/assets/images/erc/alarm_empty.png";
import undoPng from "@/assets/images/erc/alarm_undo.png";
import firePng from "@/assets/images/erc/fire.png";
import { PxMessage } from "px-ui";
import { onMounted, reactive, ref, toRefs } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const cancelRef = ref();

const state = reactive<any>({
  queryParams: {
    pageNum: 1,
    pageSize: 20,
    eqpStatus: "FIRE"
  },
  tableData: [],
  total: 0,
  cancelForm: {},
  isCancelShow: false,
  alarmId: "",
  eqpStatusList: [],
  eqpTypeList: [],
  maintainStatusList: [],
  sumValue: {}
  // updateTime: ""
});
const { queryParams, tableData, total, cancelForm, isCancelShow, alarmId, eqpStatusList, eqpTypeList, maintainStatusList, sumValue } = toRefs(state);

const tagColorList = {
  故障: "#F59E0B", // 故障
  火警: "#EF4444", // 火警
  监管: "#EE6EC6" // 监管
};

const tagBgColorList = {
  故障: "#FEF5E6", // 故障
  火警: "#FEECEC", // 火警
  监管: "#FFE9F8" // 监管
};

const tagBorderColorList = {
  故障: "#FCE2B6", // 故障
  火警: "#FAC7C7", // 火警
  监管: "#FFBAE9" // 监管
};

const getStatus = async () => {
  maintainStatusList.value = await getStatusList({});
};

const getEnum = async () => {
  const res: any = await getAlarmEnum();
  eqpStatusList.value = Object.keys(res.ALARM_EQP_STATUS).map((item, index) => ({
    id: index + 1,
    value: item,
    label: res.ALARM_EQP_STATUS[item]
  }));
};

const getNum = async () => {
  sumValue.value = await getAlarmCount();
};

// 查询列表
const queryTable = async () => {
  const params = JSON.parse(JSON.stringify(queryParams.value));
  const { time } = queryParams.value;

  const data = await queryAlarmList({
    responseStatus: ["UNRESPONSE"],
    startTime: time && time[0] ? `${time[0]} 00:00:00` : "",
    endTime: time && time[1] ? `${time[1]} 23:59:59` : "",
    ...params
  });
  tableData.value = data?.data || [];
  // if (tableData.value.length !== 0) {
  //   updateTime.value = tableData.value[0].alarmTime;
  // } else {
  //   updateTime.value = Date.now();
  // }
  total.value = data?.total;
};
// 重置筛选条件列表
const resetTable = async () => {
  queryParams.value = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    eqpStatus: "FIRE"
  };
  queryTable();
};

const queryTree = async () => {
  const data: any = await searchTreeLedger({
    name: ""
  });
  eqpTypeList.value = data;
};

// 进入页面时触发
onMounted(async () => {
  getNum();
  queryTree();
  getEnum();
  getStatus();
  queryTable();
});

const handleClear = (row: any) => {
  alarmId.value = row.alarmId;
  isCancelShow.value = true;
};

import dayjs from "dayjs";

const handleMaintain = (row: any) => {
  const { eqpName, eqpStatus } = row;
  const title = `${dayjs(Date.now()).format("YYYY/MM/DD")}-${eqpName || ""}${eqpStatus}`;
  router.push(`/erc/maintain?eqpId=${row.eqpId}&alarmId=${row.id}&title=${title}`);
};

const handleView = (row: any) => {
  router.push(`/erc/maintain/detail?eqpId=${row.eqpId}&alarmId=${row.id}`);
};

const handleCancelCancel = () => {
  cancelRef.value.resetFields();
  isCancelShow.value = false;
};

const handleSubmitCancelForm = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      await updateAlarm({ alarmId: alarmId.value, ...cancelForm.value });
      PxMessage.success("报警消除成功");
      handleCancelCancel();
      queryTable();
    }
  });
};
</script>

<style lang="scss" scoped>
@import url("@/views/erc/scss/table-list.scss");

.equip-wrap-common {
  height: calc(100vh - 270px);

  .empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    height: 100%;
    padding-top: 200px;

    img {
      width: 160px;
      height: 160px;
    }

    p {
      font-size: 16px;
      color: #909399;
    }
  }
}

.banner {
  position: relative;
  box-sizing: border-box;
  display: flex;
  flex-direction: row;
  align-items: center;
  width: 100%;
  padding: 16px;
  margin: 16px 0;
  background-color: #fff;
  border-radius: 8px;

  .left {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 324px;

    div:first-child {
      display: flex;
      flex-direction: column;
      align-items: left;

      .time {
        height: 44px;
        font-size: 44px;
        font-weight: 600;
        line-height: 44px;
        color: #13c2c2;
      }

      .date {
        height: 20px;
        margin-top: 6px;
        font-size: 14px;
        font-weight: 600;
        line-height: 20px;
        color: #7997a8;
      }
    }

    div:nth-child(2) {
      img {
        width: 56px;
        height: 44px;
        margin-top: 6px;
      }
    }
  }

  .middle {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 392px;
    height: 80px;
    margin: 0 16px;
    background: #fff linear-gradient(180deg, rgb(245 158 11 / 0%) 0%, rgb(245 158 11 / 8%) 100%);
    border: 1px solid #dcdcdc;
    border-radius: 4px;

    img {
      width: 58px;
      height: 61px;
    }

    .title {
      p:first-child {
        font-size: 14px;
        color: rgb(0 0 0 / 80%);
      }

      p:nth-child(2) {
        font-size: 22px;
        font-weight: 500;
        color: rgb(0 0 0 / 90%);
      }
    }
  }

  .right {
    display: flex;
    flex-direction: row;
    align-items: center;
    width: 392px;
    height: 80px;
    background: #fff linear-gradient(180deg, rgb(239 68 68 / 0%) 0%, rgb(239 68 68 / 8%) 100%);
    border: 1px solid #dcdcdc;
    border-radius: 4px;

    img {
      width: 61px;
      height: 60px;
    }

    .title {
      p:first-child {
        font-size: 14px;
        color: rgb(0 0 0 / 80%);
      }

      p:nth-child(2) {
        font-size: 22px;
        font-weight: 500;
        color: rgb(0 0 0 / 90%);
      }
    }
  }
}

.status {
  box-sizing: border-box;
  display: inline-flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  height: 22px;
  padding: 3px 10px;
  font-size: 12px;
  line-height: 22px;
  border-radius: 4px;

  img {
    width: 16px;
    height: 16px;
  }
}
</style>
